package com.project.utils;


import com.project.entity.system.menu.MenuTreeEntity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author : Mr.Yan
 * @program : com.project.utils
 * @create : 2020/03/31
 * @description :
 */
public class MenuSuperiorUtil {

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @return String
     */
    public static List<MenuTreeEntity> getChildPerms(List<MenuTreeEntity> list, String parentMenuId) {
        List<MenuTreeEntity> returnList = new ArrayList<MenuTreeEntity>();
        for (Iterator<MenuTreeEntity> iterator = list.iterator(); iterator.hasNext(); ) {
            MenuTreeEntity t = (MenuTreeEntity) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentMenuId().equals(parentMenuId)) {
                // 第一层
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private static void recursionFn(List<MenuTreeEntity> list, MenuTreeEntity t) {
        if (hasChild(list, t)) {
            // 得到子节点列表
            List<MenuTreeEntity> childList = getChildList(list, t);
            t.setChildren(childList);
            for (MenuTreeEntity tChild : childList) {
                if (hasChild(list, tChild)) {
                    // 判断是否有子节点
                    Iterator<MenuTreeEntity> it = childList.iterator();
                    while (it.hasNext()) {
                        MenuTreeEntity n = (MenuTreeEntity) it.next();
                        recursionFn(list, n);
                    }
                }
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<MenuTreeEntity> list, MenuTreeEntity t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 得到子节点列表
     */
    private static List<MenuTreeEntity> getChildList(List<MenuTreeEntity> list, MenuTreeEntity t) {
        List<MenuTreeEntity> tlist = new ArrayList<MenuTreeEntity>();
        Iterator<MenuTreeEntity> it = list.iterator();
        while (it.hasNext()) {
            MenuTreeEntity n = (MenuTreeEntity) it.next();
            if (n.getParentMenuId().equals(t.getMenuId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
